<template>
  <div class="app-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>维度管理</span>
          <el-button
            type="primary"
            @click="handleAdd"
          >新增维度</el-button>
        </div>
      </template>

      <!-- 搜索区域 -->
      <div class="search-box">
        <el-form :inline="true" :model="queryParams">
          <el-form-item label="所属测试">
            <el-select
              v-model="queryParams.testId"
              placeholder="请选择测试"
              clearable
              style="width: 200px;"
            >
              <el-option
                v-for="item in testOptions"
                :key="item.id"
                :label="item.title"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="维度名称">
            <el-input
              v-model="queryParams.dimensionName"
              placeholder="请输入维度名称"
              clearable
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleQuery">查询</el-button>
            <el-button @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <el-table
        v-loading="loading"
        :data="dimensionList"
        border
        style="width: 100%"
      >
        <el-table-column
          prop="dimensionKey"
          label="维度键"
          width="180"
          align="center"
        />
        <el-table-column
          prop="dimensionName"
          label="维度名称"
          width="180"
          align="center"
        />
        <el-table-column
          prop="testTitle"
          label="所属测试"
          align="center"
        />
        <el-table-column
          prop="scoreRange"
          label="分数范围"
          align="center"
        />
        <el-table-column
          prop="weight"
          label="权重"
          width="100"
          align="center"
        />
        <el-table-column
          label="操作"
          width="180"
          align="center"
        >
          <template #default="scope">
            <el-button
              type="primary"
              link
              @click="handleEdit(scope.row)"
            >编辑</el-button>
            <el-button
              type="danger"
              link
              @click="handleDelete(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
    </el-card>

    <!-- 添加/修改维度对话框 -->
    <el-dialog
      :title="title"
      v-model="open"
      width="500px"
      append-to-body
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="所属测试" prop="testId">
          <el-select
            v-model="form.testId"
            placeholder="请选择所属测试"
            style="width: 100%"
          >
            <el-option
              v-for="item in testOptions"
              :key="item.id"
              :label="item.title"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="维度键" prop="dimensionKey">
          <el-input v-model="form.dimensionKey" placeholder="请输入维度键" />
        </el-form-item>
        <el-form-item label="维度名称" prop="dimensionName">
          <el-input v-model="form.dimensionName" placeholder="请输入维度名称" />
        </el-form-item>
        <el-form-item label="分数范围" prop="scoreRange">
          <el-input v-model="form.scoreRange" placeholder="请输入分数范围,如: 0-100" />
        </el-form-item>
        <el-form-item label="权重" prop="weight">
          <el-input-number v-model="form.weight" :min="0" :max="100" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, onMounted, reactive } from 'vue'
import { listTests } from '@/api/psychological-test'
import { getDimensionList, createDimension, updateDimension, deleteDimension } from '@/api/dimension'
import type { DimensionQuery, Dimension, DimensionForm } from '@/types/dimension'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance } from 'element-plus'

const loading = ref(false)
const total = ref(0)
const open = ref(false)
const title = ref('')
const dimensionList = ref<Dimension[]>([])
const testOptions = ref<{ id: number; title: string }[]>([])

const queryParams = reactive<DimensionQuery>({
  pageNum: 1,
  pageSize: 10,
  testId: undefined,
  dimensionName: ''
})

const form = ref<DimensionForm>({
  testId: 0,
  dimensionKey: '',
  dimensionName: '',
  scoreRange: '',
  weight: 1
})

const rules = {
  testId: [{ required: true, message: '请选择所属测试', trigger: 'change' }],
  dimensionKey: [{ required: true, message: '请输入维度键', trigger: 'blur' }],
  dimensionName: [{ required: true, message: '请输入维度名称', trigger: 'blur' }],
  scoreRange: [{ required: true, message: '请输入分数范围', trigger: 'blur' }],
  weight: [{ required: true, message: '请输入权重', trigger: 'change' }]
}

const formRef = ref<FormInstance>()

// 获取维度列表
const getList = async () => {
  loading.value = true
  try {
    const res = await getDimensionList(queryParams)
    dimensionList.value = res.data.records || []
    total.value = res.data.total
  } catch (err) {
    console.error('获取维度列表失败:', err)
  } finally {
    loading.value = false
  }
}

// 获取测试列表
const getTestOptions = async () => {
  try {
    const res = await listTests({ pageNum: 1, pageSize: 1000 })
    testOptions.value = res.data.records || []
  } catch (err) {
    console.error('获取测试列表失败:', err)
  }
}

// 表单重置
const reset = () => {
  form.value = {
    testId: 0,
    dimensionKey: '',
    dimensionName: '',
    scoreRange: '',
    weight: 1
  }
}

// 取消按钮
const cancel = () => {
  open.value = false
  reset()
}

// 新增按钮操作
const handleAdd = () => {
  reset()
  open.value = true
  title.value = '添加维度'
}

// 修改按钮操作
const handleEdit = (row: Dimension) => {
  reset()
  const id = row.id
  form.value = { ...row }
  open.value = true
  title.value = '修改维度'
}

// 提交按钮
const submitForm = async () => {
  // 检查 formRef 是否已正确绑定
  if (!formRef.value) {
    ElMessage.error('表单实例未正确初始化，请刷新页面重试');
    return;
  }

  // 使用可选链操作符确保安全调用 validate 方法
  formRef.value.validate(async (valid: boolean) => {
    if (valid) {
      try {
        if (form.value.id) {
          await updateDimension(form.value.id, form.value);
          ElMessage.success('修改成功');
        } else {
          await createDimension(form.value);
          ElMessage.success('新增成功');
        }
        open.value = false;
        getList();
      } catch (err) {
        console.error('提交失败:', err);
        ElMessage.error('提交失败，请稍后重试');
      }
    } else {
      ElMessage.warning('请完善表单信息');
    }
  });
};

// 删除按钮操作
const handleDelete = (row: Dimension) => {
  ElMessageBox.confirm('是否确认删除该维度?', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteDimension(row.id)
      getList()
      ElMessage.success('删除成功')
    } catch (err) {
      console.error('删除失败:', err)
    }
  })
}

// 查询按钮
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

// 重置按钮
const resetQuery = () => {
  queryParams.testId = undefined
  queryParams.dimensionName = ''
  handleQuery()
}

onMounted(() => {
  getList()
  getTestOptions()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.dialog-footer {
  text-align: right;
  padding-top: 20px;
}

.search-box {
  margin-bottom: 20px;
}

.pagination-container {
  padding-top: 20px;
}
</style>